<script setup lang="ts">
import type { AttrInfo } from '@/api/product/type.ts';
import { ref, nextTick } from 'vue';
import type { QTableColumn, QPopupEdit } from 'quasar';
import { useQuasar } from 'quasar';
import MyQTable from '@/components/MyQTable.vue';
import { reqSaveAttrInfo } from '@/api/product/attr.ts';
import { quasarFormStyle } from '@/setting.ts';

const attrInfoForm = ref<AttrInfo>({
  categoryId: 0,
  categoryLevel: 3,
  attrName: '',
  attrValueList: []
});
// 展示表单
function showCard(attrInfo: AttrInfo | number) {
  if (typeof attrInfo === 'number') {
    attrInfoForm.value = {
      categoryId: attrInfo,
      categoryLevel: 3,
      attrName: '',
      attrValueList: []
    };
    return;
  }
  // 深拷贝
  attrInfoForm.value = JSON.parse(JSON.stringify(attrInfo));
}
defineExpose({ showCard });
const $emit = defineEmits(['hideFormCard']);
// 表格数据
const columns: QTableColumn[] = [
  {
    name: 'index',
    label: '序号',
    field: '',
    align: 'center',
    style: 'width: 80px'
  },
  { name: 'valueName', label: '属性值', field: 'valueName', align: 'left' },
  { name: 'control', label: '操作', field: 'id', align: 'left' }
];
// 多个同名ref获取到的是最后一个
// 判断并对最后一个td进行处理
// 存储最后一个属性值q-popup-edit
let pushLastTd: QPopupEdit;
function handlePushTd<T>(el: T, index: number) {
  if (index + 1 === attrInfoForm.value.attrValueList.length) {
    pushLastTd = el as QPopupEdit;
  }
}
// 添加属性值
function addAttrValue() {
  attrInfoForm.value.attrValueList.push({
    id: 0,
    valueName: ''
  });
  nextTick(() => {
    pushLastTd.show();
  });
}
// 删除属性值
function removeAttrValue(index: number) {
  attrInfoForm.value.attrValueList.splice(index, 1);
}
// 取消编辑
function cancelPopup(value: string, index: number) {
  console.log('cs');
  isEditing.value = false;
  error.value = false;
  if (!value) {
    removeAttrValue(index);
  }
}
// 验证属性值
const error = ref(false);
const errorMessage = ref('');
function validateAttrValue(value: string) {
  if (value.trim() === '') {
    error.value = true;
    errorMessage.value = '属性值不能为空';
    return false;
  } else {
    error.value = false;
    errorMessage.value = '';
    return true;
  }
}
// 文本框是否正在编辑
const isEditing = ref<boolean>(false);
// 提交数据
const $q = useQuasar();
async function submitForm() {
  const result = await reqSaveAttrInfo(attrInfoForm.value);
  try {
    if (result.code === 200) {
      $q.notify({
        type: 'positive',
        message: '提交成功',
        position: 'top'
      });
      $emit('hideFormCard', 'ok');
    } else {
      throw new Error('提交失败');
    }
  } catch (error: any) {
    $q.notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  }
}
</script>

<template>
  <q-card class="q-mt-md">
    <q-card-section>
      <q-input
        type="text"
        label="属性名"
        v-bind="quasarFormStyle"
        style="width: 240px"
        v-model.trim="attrInfoForm!.attrName"
      />
    </q-card-section>
    <q-card-section>
      <q-btn
        color="primary"
        label="添加属性值"
        icon="add"
        class="q-mr-md"
        :disable="!attrInfoForm?.attrName || isEditing"
        @click="addAttrValue"
        v-bind="quasarFormStyle"
      />
    </q-card-section>
    <q-card-section>
      <my-q-table :data="attrInfoForm.attrValueList" :columns="columns">
        <template #body-cell-valueName="props">
          <q-td key="valueName">
            {{ props.row.valueName }}
            <q-popup-edit
              v-model="props.row.valueName"
              v-slot="scope"
              :validate="validateAttrValue"
              @show="isEditing = true"
              @hide="() => cancelPopup(props.row.valueName, props.pageIndex)"
              :ref="el => handlePushTd(el, props.pageIndex)"
            >
              <q-input
                v-model.trim="scope.value"
                dense
                autofocus
                hint="属性值"
                @keyup.enter="scope.set"
                :error="error"
                :error-message="errorMessage"
              >
                <template #after>
                  <q-btn
                    icon="check_circle"
                    @click="scope.set"
                    color="positive"
                    size="xs"
                    round
                    class="q-ml-lg"
                  ></q-btn>
                </template>
              </q-input>
            </q-popup-edit>
          </q-td>
        </template>
        <template #body-cell-control="{ pageIndex }">
          <q-td>
            <q-btn
              icon="delete"
              color="negative"
              size="xs"
              @click="removeAttrValue(pageIndex)"
              :disable="isEditing"
            ></q-btn>
          </q-td>
        </template>
      </my-q-table>
    </q-card-section>
    <q-card-section>
      <q-btn
        label="保存"
        color="primary"
        class="q-mr-md"
        :disable="
          attrInfoForm.attrValueList.length <= 0 ||
          !attrInfoForm.attrName ||
          isEditing
        "
        @click="submitForm"
      />
      <q-btn label="取消" color="primary" flat @click="$emit('hideFormCard')" />
    </q-card-section>
  </q-card>
</template>

<style scoped></style>
